package com.oracle.lingshangejia.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.TaskReprotingAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.ImgBean;
import com.oracle.lingshangejia.bean.TaskReprotingBean;
import com.oracle.lingshangejia.utils.SpUtils;
import com.oracle.lingshangejia.view.PictureSelectorConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

/**
 * 任务上报
 */
public class TaskReportingActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_title;
    private ImageButton ib_back;
    private EditText et_task_content;
    private ImageView iv_task_addimg;
    private ImageView iv_task1;//拍照
    private ImageView iv_task2;
    private ImageView iv_task3; //表情
    private ImageView iv_task4;  //位置
    private RelativeLayout rl_taskreport_ok; //上报
    private TaskReprotingAdapter mGridViewAddImgAdapter;
    private GridView gridView;
    private ArrayList<String> mPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private int outid;
    private AlertDialog alertDialog;
    private AlertDialog mDialog;
    private static final int NOT_NOTICE = 2;//如果勾选了不再询问
    @Override
    public int intiLayout() {
        return R.layout.activity_taskreporting;
    }

    @Override
    public void initView() {
        tv_title=findViewById(R.id.tv_title);
        ib_back=findViewById(R.id.ib_back);
        gridView=findViewById(R.id.gridView);
        et_task_content=findViewById(R.id.et_task_content);
        iv_task_addimg=findViewById(R.id.iv_task_addimg);
        iv_task1=findViewById(R.id.iv_task1);
        iv_task2=findViewById(R.id.iv_task2);
        iv_task3=findViewById(R.id.iv_task3);
        iv_task4=findViewById(R.id.iv_task4);
        iv_task4.setOnClickListener(this);
        rl_taskreport_ok=findViewById(R.id.rl_taskreport_ok);
        ib_back.setOnClickListener(this);
        iv_task_addimg.setOnClickListener(this);
        rl_taskreport_ok.setOnClickListener(this);
        tv_title.setText("任务上报");

        if(getIntent()!=null){
            outid=getIntent().getIntExtra("outid",0);
        }

        initGridView();
    }
    //初始化展示上传图片的GridView
    private void initGridView() {
        mGridViewAddImgAdapter = new TaskReprotingAdapter(TaskReportingActivity.this, mPicList);
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == parent.getChildCount() - 1) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过5张，才能点击
                    if (mPicList.size() == 6) {
                        //最多添加5张图片
                        viewPluImg(position);
                    } else {
                        //添加凭证图片
                        selectPic(6 - mPicList.size());
                    }
                } else {
                    viewPluImg(position);
                }
            }
        });
    }
    //查看大图
    private void viewPluImg(int position) {
        Intent intent = new Intent(TaskReportingActivity.this, PlusImageActivity.class);
        intent.putStringArrayListExtra(Constant.IMG_LIST, mPicList);
        intent.putExtra(Constant.POSITION, position);
        startActivityForResult(intent, Constant.REQUEST_CODE_MAIN);
    }

    /**
     * 打开相册或者照相机选择凭证图片，最多5张
     *
     * @param maxTotal 最多选择的图片的数量
     */
    private void selectPic(int maxTotal) {
        PictureSelectorConfig.initMultiConfig(this, maxTotal);
    }

    // 处理选择的照片的地址
    private void refreshAdapter(List<LocalMedia> picList) {
        for (LocalMedia localMedia : picList) {
            //被压缩后的图片路径
            if (localMedia.isCompressed()) {
                String compressPath = localMedia.getCompressPath(); //压缩后的图片路径
                mPicList.add(compressPath); //把图片添加到将要上传的图片数组中
                mGridViewAddImgAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    refreshAdapter(PictureSelector.obtainMultipleResult(data));
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
        if (requestCode == Constant.REQUEST_CODE_MAIN && resultCode == Constant.RESULT_CODE_VIEW_IMG) {
            //查看大图页面删除了图片
            ArrayList<String> toDeletePicList = data.getStringArrayListExtra(Constant.IMG_LIST); //要删除的图片的集合
            mPicList.clear();
            mPicList.addAll(toDeletePicList);
            mGridViewAddImgAdapter.notifyDataSetChanged();
        }

        if(resultCode==RESULT_OK&&requestCode==1000){
            if(data!=null){
                String result = data.getExtras().getString("address");//得到新Activity 关闭后返回的数据
                et_task_content.setText(result);
            }
        }
        if(requestCode==NOT_NOTICE){
            myRequetPermission();//由于不知道是否选择了允许所以需要再次判断
        }
    }
    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                finish();
                break;
            case R.id.rl_taskreport_ok:  //上报任务
                String content = et_task_content.getText().toString().trim();
                if (content.length() == 0 || mPicList.size()==0) {
                    Toast.makeText(this, "必须填写这一刻的想法和选择照片！", Toast.LENGTH_SHORT).show();
                    return;
                }
                postImg(content);
                break;
            case R.id.iv_task4:  //位置
                myRequetPermission();
                break;
        }
    }
    private void myRequetPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }else {
            Intent intent1=new Intent(this,PositionListActivity.class);
            startActivityForResult(intent1,1000);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {//选择了“始终允许”
                    // Toast.makeText(this, "" + "权限" + permissions[i] + "申请成功", Toast.LENGTH_SHORT).show();
                    Intent intent1=new Intent(this,PositionListActivity.class);
                    startActivityForResult(intent1,1000);
                } else {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])){//用户选择了禁止不再询问

                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("permission")
                                .setMessage("点击允许才可以使用我们的app哦")
                                .setPositiveButton("去允许", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        if (mDialog != null && mDialog.isShowing()) {
                                            mDialog.dismiss();
                                        }
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getPackageName(), null);//注意就是"package",不用改成自己的包名
                                        intent.setData(uri);
                                        startActivityForResult(intent, NOT_NOTICE);
                                    }
                                });
                        mDialog = builder.create();
                        mDialog.setCanceledOnTouchOutside(false);
                        mDialog.show();



                    }else {//选择禁止
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("permission")
                                .setMessage("点击允许才可以使用我们的app哦")
                                .setPositiveButton("去允许", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        if (alertDialog != null && alertDialog.isShowing()) {
                                            alertDialog.dismiss();
                                        }
                                        ActivityCompat.requestPermissions(TaskReportingActivity.this,
                                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                    }
                                });
                        alertDialog = builder.create();
                        alertDialog.setCanceledOnTouchOutside(false);
                        alertDialog.show();
                    }

                }
            }
        }
    }
    private void postImg(final String content){
        List<File> files=new ArrayList<>();
        for(int i=0;i<mPicList.size();i++){
            File file=new File(mPicList.get(i));
            files.add(file);
        }
        Log.e("图片",files.size()+"");
        OkGo.<String>post(Constant.baseurl+"open/uploadImg")
                .tag(this)
                .isMultipart(true)
                .addFileParams("files",files)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("上传", response.body());
                        Gson gson=new Gson();
                        ImgBean bean=gson.fromJson(response.body(),ImgBean.class);
                        if(bean.getCode()==0){
                            getNetPostTast(content,bean.getFileUrl());
                        }else{
                            Toast.makeText(TaskReportingActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        }

                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(TaskReportingActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
                    }
                });

    }
    private void getNetPostTast(String content, List<Integer> fileUrl) {
        String token= (String) SpUtils.get(TaskReportingActivity.this,"token","");
        int ysid= (int) SpUtils.get(TaskReportingActivity.this,"ysid",0);
        int mark= (int) SpUtils.get(TaskReportingActivity.this,"mark",0);
        JSONObject object=new JSONObject();
        try {
            object.put("token",token);
            object.put("rwId",outid);
            object.put("mark",mark);
            object.put("sqysId",ysid);
            object.put("rwsm",content);
            for(int i=0;i<fileUrl.size();i++){
                object.put("picid"+(i+1),fileUrl.get(i)+"");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.<String>post(Constant.baseurl+"online/wqrw/tjrw")
                .tag(this)
                .upJson(object.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("上传", response.body());
                        Gson gson=new Gson();
                        TaskReprotingBean bean=gson.fromJson(response.body(),TaskReprotingBean.class);
                        if (bean.getCode()==0) {
                            Toast.makeText(TaskReportingActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                            finish();
                        }else{
                            Toast.makeText(TaskReportingActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(TaskReportingActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
                    }
                });
    }

}
